module ESI
  class BaseParser
    def initialize(router,cache)
      @@fragment_cache ||= cache
      @cache = @@fragment_cache
      @router = router
    end

    # :startdoc:
    # scans the fragment url, replacing occurrances of $(VAR{ ..  with the given value read from
    # the HTTP Request object
    # :enddoc:
    def prepare_url_vars(url,request)
      # scan url  for $(VAR{
      begin
        # using the regex look for url vars that get set via http params
        # for each var extract the value and store it in the operations array
        operations = []
        url.scan(/\$\([0-9a-zA-Z_{}]+\)/x) do|var|
          # extract the var name
          name = var.gsub(/\$\(/,'').gsub(/\{.*$/,'')
          key = var.gsub(/^.*\{/,'').gsub(/\}.*$/,'')
          value = Mongrel::HttpRequest.query_parse(request.params[name])[key]
          operations << {:sub => var, :with => (value||"")}
        end
        # apply each operation to the url
        operations.each { |op| url.gsub!(op[:sub],op[:with]) }
      rescue Exception => e
        $logger.error "Fatal => #{e}"
        $logger.error e.backtrace
      end
      url
    end
  end
end
